package com.UnionPayCenter.controller;

import com.UnionPayCenter.account.enums.PayStatusEnum;
import com.UnionPayCenter.constant.ComponentConstants;
import com.UnionPayCenter.constant.ConstantInterface;
import com.UnionPayCenter.entity.ChannelEntity;
import com.UnionPayCenter.entity.ComponentExamineLogEntity;
import com.UnionPayCenter.entity.ResponseWrapper;
import com.UnionPayCenter.entity.UserLevelEntity;
import com.UnionPayCenter.entity.vo.ComponentGrantInfoVo;
import com.UnionPayCenter.entity.vo.TemplateDraftVo;
import com.UnionPayCenter.entity.vo.TemplateVo;
import com.UnionPayCenter.enums.ErrorCodeEnum;
import com.UnionPayCenter.exception.ApiException;
import com.UnionPayCenter.jwt.CurrentManager;
import com.UnionPayCenter.jwt.CurrentShop;
import com.UnionPayCenter.service.FundsAccountService;
import com.UnionPayCenter.service.IComponentService;
import com.UnionPayCenter.service.IUserService;
import com.UnionPayCenter.service.IWechatService;
import com.UnionPayCenter.swagger.ApiJsonObject;
import com.UnionPayCenter.swagger.ApiJsonProperty;
import com.UnionPayCenter.util.StringUtils;
import com.UnionPayCenter.wechat.WeixinUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @program: UnionPayCenter
 * @description: 微信第三方接口
 * @author: bite
 * @create:
 **/
@Slf4j
@RestController
@Api(value = "component", tags = "微信第三方接口")
@RequestMapping("/component")
public class ComponentController {
    @Autowired
    private IComponentService componentService;

//    /**
//     * @Description: 接收授权码回调
//     * @Param:
//     * @return:
//     * @Author: bite
//     * @Date: 2019/7/21
//     */
//    @RequestMapping(value="/authCodeBack/{shopId}")
//    @ApiOperation(tags = "微信回调", value = "[微信]接收授权码回调", response = String.class)
//    public String wechatAuthCodeBack(@PathVariable(value = "shopId") Integer shopId,
//                                     @RequestParam(value = "auth_code") String authCode,
//                                    @RequestParam(value = "expires_in") String expiresIn) throws Exception {
//
//        //获取授权码
//        log.info(String.format("接收授权码回调 authCode:%s, expiresIn: %s", authCode, expiresIn));
//        componentService.authCodeBack(shopId, authCode);
//
//        return "close";
//    }

    @CurrentManager
    @CurrentShop
    @RequestMapping(value = "/findAuthUrl", method = RequestMethod.POST)
    @ApiOperation(tags = "微信第三方接口", httpMethod = "POST", value = "[后台]微信第三方接口获取授权链接", response = String.class)
    public ResponseWrapper findAuthUrl(
            @ApiJsonObject(name = "componentFindAuthUrlParams", value = {
                    @ApiJsonProperty(key = "token", value = "token值"),
                    @ApiJsonProperty(key = "shopId", value = "商铺id", type = "int"),
                    @ApiJsonProperty(key = "type", value = "1-公众号 2-小程序 3-公众号/小程序", required = false, defaultValue = "3")
            }) @RequestBody JSONObject jsonParam) {
        try {
            String url = componentService.findAuthUrl(jsonParam);
            return ResponseWrapper.succeed(url);
        }catch (ApiException e){
            log.error(String.format("[后台]微信第三方接口获取授权链接失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        }catch (Exception e){
            log.error(String.format("[后台]微信第三方接口获取授权链接失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }

    @CurrentManager
    @CurrentShop
    @RequestMapping(value = "/openBind", method = RequestMethod.POST)
    @ApiOperation(tags = "微信第三方接口", httpMethod = "POST", value = "[后台]微信第三方接口绑定开发平台", response = boolean.class)
    public ResponseWrapper openBind(
            @ApiJsonObject(name = "componentOpenBindParams", value = {
                    @ApiJsonProperty(key = "token", value = "token值"),
                    @ApiJsonProperty(key = "shopId", value = "商铺id", type = "int")
            }) @RequestBody JSONObject jsonParam) {
        try {
            boolean isSucc = componentService.openBind(jsonParam);
            return ResponseWrapper.succeed(isSucc);
        }catch (ApiException e){
            log.error(String.format("[后台]微信第三方接口绑定开发平台失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        }catch (Exception e){
            log.error(String.format("[后台]微信第三方接口绑定开发平台失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }

    @CurrentManager
    @RequestMapping(value = "/findAuthList", method = RequestMethod.POST)
    @ApiOperation(tags = "微信第三方接口", httpMethod = "POST", value = "[超管]查询商铺授权列表", response = ComponentGrantInfoVo.class)
    public ResponseWrapper findAuthList(
            @ApiJsonObject(name = "componentFindAuthListParams", value = {
                    @ApiJsonProperty(key = "token", value = "token值"),
                    @ApiJsonProperty(key = "page", value = "页数", type = "int", required = false),
                    @ApiJsonProperty(key = "pageSize", value = "每页条数", type = "int", required = false),
                    @ApiJsonProperty(key = "status", value = "状态 0-审核成功 1-审核被拒 2-审核中 3-已撤回 4-发布成功 5-待审核", required = false),
                    @ApiJsonProperty(key = "appName", value = "小程序名称", required = false)
            }) @RequestBody JSONObject jsonParam) {
        try {
            PageInfo<ComponentGrantInfoVo> list = componentService.findAuthList(jsonParam);
            return ResponseWrapper.succeed(list);
        }catch (ApiException e){
            log.error(String.format("[超管]查询商铺授权列表失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        }catch (Exception e){
            log.error(String.format("[超管]查询商铺授权列表失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }

    @CurrentManager
    @RequestMapping(value = "/findTemplateDraftList", method = RequestMethod.POST)
    @ApiOperation(tags = "微信第三方接口", httpMethod = "POST", value = "[超管]查询代码草稿列表", response = TemplateDraftVo.class)
    public ResponseWrapper findTemplateDraftList(
            @ApiJsonObject(name = "componentFindTemplateDraftListParams", value = {
                    @ApiJsonProperty(key = "token", value = "token值")
            }) @RequestBody JSONObject jsonParam) {
        try {
            PageInfo<TemplateDraftVo> list = componentService.findTemplateDraftList(jsonParam);
            return ResponseWrapper.succeed(list);
        }catch (ApiException e){
            log.error(String.format("[超管]查询代码草稿列表失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        }catch (Exception e){
            log.error(String.format("[超管]查询代码草稿列表失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }

    @CurrentManager
    @RequestMapping(value = "/addToTemplate", method = RequestMethod.POST)
    @ApiOperation(tags = "微信第三方接口", httpMethod = "POST", value = "[超管]添加到代码库", response = boolean.class)
    public ResponseWrapper addTemplate(
            @ApiJsonObject(name = "componentAddToTemplateParams", value = {
                    @ApiJsonProperty(key = "token", value = "token值"),
                    @ApiJsonProperty(key = "draftId", value = "草稿 id")
            }) @RequestBody JSONObject jsonParam) {
        try {
            String draftId = jsonParam.getString("draftId");
            if(StringUtils.isNullStr(draftId)){
                return ResponseWrapper.failed(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "draftId"));
            }
            boolean isSucc = componentService.addToTemplate(jsonParam);
            return ResponseWrapper.succeed(isSucc);
        }catch (ApiException e){
            log.error(String.format("[超管]添加到代码库失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        }catch (Exception e){
            log.error(String.format("[超管]添加到代码库失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }

    @CurrentManager
    @RequestMapping(value = "/findTemplateList", method = RequestMethod.POST)
    @ApiOperation(tags = "微信第三方接口", httpMethod = "POST", value = "[超管]查询代码模板列表", response = TemplateVo.class)
    public ResponseWrapper findTemplateList(
            @ApiJsonObject(name = "componentFindTemplateListParams", value = {
                    @ApiJsonProperty(key = "token", value = "token值")
            }) @RequestBody JSONObject jsonParam) {
        try {
            PageInfo<TemplateVo> list = componentService.findTemplateList(jsonParam);
            return ResponseWrapper.succeed(list);
        }catch (ApiException e){
            log.error(String.format("[超管]查询代码模板列表失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        }catch (Exception e){
            log.error(String.format("[超管]查询代码模板列表失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }

    @CurrentManager
    @RequestMapping(value = "/deleteTemplate", method = RequestMethod.POST)
    @ApiOperation(tags = "微信第三方接口", httpMethod = "POST", value = "[超管]删除代码库模版", response = boolean.class)
    public ResponseWrapper deleteTemplate(
            @ApiJsonObject(name = "componentDeleteTemplateParams", value = {
                    @ApiJsonProperty(key = "token", value = "token值"),
                    @ApiJsonProperty(key = "templateId", value = "要删除的模版 ID")
            }) @RequestBody JSONObject jsonParam) {
        try {
            String templateId = jsonParam.getString("templateId");
            if(StringUtils.isNullStr(templateId)){
                return ResponseWrapper.failed(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "templateId"));
            }
            boolean isSucc = componentService.deleteTemplate(jsonParam);
            return ResponseWrapper.succeed(isSucc);
        }catch (ApiException e){
            log.error(String.format("[超管]删除代码库模版失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        }catch (Exception e){
            log.error(String.format("[超管]删除代码库模版失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }

    @CurrentManager
    @CurrentShop
    @RequestMapping(value = "/submitAudit", method = RequestMethod.POST)
    @ApiOperation(tags = "微信第三方接口", httpMethod = "POST", value = "[超管]单独提交审核, 提交审核失败/已撤回/待审核的", response = boolean.class)
    public ResponseWrapper submitAudit(
            @ApiJsonObject(name = "componentSubmitAuditParams", value = {
                    @ApiJsonProperty(key = "token", value = "token值"),
                    @ApiJsonProperty(key = "templateId", value = "模版 ID"),
                    @ApiJsonProperty(key = "userVersion", value = "代码版本号"),
                    @ApiJsonProperty(key = "userDesc", value = "代码描述"),
                    @ApiJsonProperty(key = "shopId", value = "商铺id")
            }) @RequestBody JSONObject jsonParam) {
        try {
            String templateId = jsonParam.getString("templateId");
            if(StringUtils.isNullStr(templateId)){
                return ResponseWrapper.failed(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "templateId"));
            }
            String userVersion = jsonParam.getString("userVersion");
            if(StringUtils.isNullStr(userVersion)){
                return ResponseWrapper.failed(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "userVersion"));
            }
            String userDesc = jsonParam.getString("userDesc");
            if(StringUtils.isNullStr(userDesc)){
                return ResponseWrapper.failed(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "userDesc"));
            }

            boolean isSucc = componentService.submitAudit(jsonParam);
            return ResponseWrapper.succeed(isSucc);
        }catch (ApiException e){
            log.error(String.format("[超管]单独提交审核失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        }catch (Exception e){
            log.error(String.format("[超管]单独提交审核失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }

    @CurrentManager
    @RequestMapping(value = "/allSubmitAudit", method = RequestMethod.POST)
    @ApiOperation(tags = "微信第三方接口", httpMethod = "POST", value = "[超管]全部提交审核， 只提交待审核的", response = boolean.class)
    public ResponseWrapper allSubmitAudit(
            @ApiJsonObject(name = "componentAllSubmitAuditParams", value = {
                    @ApiJsonProperty(key = "token", value = "token值"),
                    @ApiJsonProperty(key = "templateId", value = "模版 ID"),
                    @ApiJsonProperty(key = "userVersion", value = "代码版本号"),
                    @ApiJsonProperty(key = "userDesc", value = "代码描述")
            }) @RequestBody JSONObject jsonParam) {
        try {
            String templateId = jsonParam.getString("templateId");
            if(StringUtils.isNullStr(templateId)){
                return ResponseWrapper.failed(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "templateId"));
            }
            String userVersion = jsonParam.getString("userVersion");
            if(StringUtils.isNullStr(userVersion)){
                return ResponseWrapper.failed(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "userVersion"));
            }
            String userDesc = jsonParam.getString("userDesc");
            if(StringUtils.isNullStr(userDesc)){
                return ResponseWrapper.failed(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "userDesc"));
            }

            boolean isSucc = componentService.allSubmitAudit(jsonParam);
            return ResponseWrapper.succeed(isSucc);
        }catch (ApiException e){
            log.error(String.format("[超管]全部提交审核失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        }catch (Exception e){
            log.error(String.format("[超管]全部提交审核失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }

    @CurrentManager
    @CurrentShop
    @RequestMapping(value = "/release", method = RequestMethod.POST)
    @ApiOperation(tags = "微信第三方接口", httpMethod = "POST", value = "[超管]单独发布", response = boolean.class)
    public ResponseWrapper release(
            @ApiJsonObject(name = "componentReleaseParams", value = {
                    @ApiJsonProperty(key = "token", value = "token值"),
                    @ApiJsonProperty(key = "shopId", value = "商铺id")
            }) @RequestBody JSONObject jsonParam) {
        try {

            boolean isSucc = componentService.release(jsonParam);
            return ResponseWrapper.succeed(isSucc);
        }catch (ApiException e){
            log.error(String.format("[超管]单独发布失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        }catch (Exception e){
            log.error(String.format("[超管]单独发布失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }

    @CurrentManager
    @RequestMapping(value = "/allRelease", method = RequestMethod.POST)
    @ApiOperation(tags = "微信第三方接口", httpMethod = "POST", value = "[超管]全部发布", response = boolean.class)
    public ResponseWrapper allRelease(
            @ApiJsonObject(name = "componentAllReleaseParams", value = {
                    @ApiJsonProperty(key = "token", value = "token值")
            }) @RequestBody JSONObject jsonParam) {
        try {

            boolean isSucc = componentService.allRelease(jsonParam);
            return ResponseWrapper.succeed(isSucc);
        }catch (ApiException e){
            log.error(String.format("[超管]全部发布失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        }catch (Exception e){
            log.error(String.format("[超管]全部发布失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }

    @CurrentManager
    @CurrentShop
    @RequestMapping(value = "/findLastExamineStatus", method = RequestMethod.POST)
    @ApiOperation(tags = "微信第三方接口", httpMethod = "POST", value = "[超管]单独查询最后一次审核状态", response = ComponentExamineLogEntity.class)
    public ResponseWrapper findLastExamineStatus(
            @ApiJsonObject(name = "componentFindLastExamineStatusParams", value = {
                    @ApiJsonProperty(key = "token", value = "token值"),
                    @ApiJsonProperty(key = "shopId", value = "商铺id")
            }) @RequestBody JSONObject jsonParam) {
        try {

            ComponentExamineLogEntity entity = componentService.findLastExamineStatus(jsonParam);
            return ResponseWrapper.succeed(entity);
        }catch (ApiException e){
            log.error(String.format("[超管]单独查询最后一次审核状态失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        }catch (Exception e){
            log.error(String.format("[超管]单独查询最后一次审核状态失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }
}
